package com.hafu.dao;

import com.hafu.model.Student;
import com.hafu.util.DbUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    private Connection conn;

    public StudentDao() {
        this.conn = DbUtil.getConn();
    }

    /**
     * 查询所有学生信息
     */
    public List<Student> getAllStudents() {
        List<Student> students = new ArrayList<>();
        String sql = "SELECT * FROM student";

        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                Student student = new Student();
                student.setStudentId(rs.getString("student_id"));
                student.setName(rs.getString("name"));
                student.setGender(rs.getString("gender"));
                student.setAge(rs.getInt("age"));
                student.setMajor(rs.getString("major"));
                student.setEnrollmentDate(rs.getDate("enrollment_date"));
                student.setPhone(rs.getString("phone"));
                students.add(student);
            }
        } catch (SQLException e) {
            handleSQLException("查询所有学生失败", e);
        }

        return students;
    }

    /**
     * 新增学生（示例，可根据需求扩展）
     */
    public boolean addStudent(Student student) {
        String sql = "INSERT INTO student (student_id, name, gender, age, major, enrollment_date, phone) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, student.getStudentId());
            pstmt.setString(2, student.getName());
            pstmt.setString(3, student.getGender());
            pstmt.setInt(4, student.getAge());
            pstmt.setString(5, student.getMajor());
            pstmt.setDate(6, new java.sql.Date(student.getEnrollmentDate().getTime()));
            pstmt.setString(7, student.getPhone());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            handleSQLException("新增学生失败", e);
            return false;
        }
    }

    private void handleSQLException(String operation, SQLException e) {
        System.err.println(operation + ": " + e.getMessage());
        e.printStackTrace();
    }
}